package xyj.sparrow.common.netty.util;

import xyj.sparrow.common.netty.bean.Request;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

/**
 * @ClassName ProtostuffUtils
 * @Description TODO
 * @Author Jim
 * @Date 2021/1/15 20:42
 * @Version 1.0.0
 **/
public class ProtostuffUtil {
    public static void main(String[] args) {
        Request request = new Request();
        request.setClassName("xyj.sparrow.common.netty.service.CancelServiceImpl");
        request.setMethodName("cancel");
        Object[] params = new Object[2];
        params[0] = "Jack";
        params[1] = 12;
        request.setParams(params);
        Class[] paramType = new Class[2];
        paramType[0] = params[0].getClass();
        paramType[1] = params[1].getClass();
        request.setParamTypes(paramType);
        request.setRequestType(Request.RequestType.TRANSFER);
        byte[] serialize = serialize(request);
        Request copy = deserialize(serialize);
    }

    private static class SerializeData {
        private Object target;
    }

    @SuppressWarnings("unchecked")
    public static byte[] serialize(Object object) {
        SerializeData serializeData = new SerializeData();
        serializeData.target = object;
        Class<SerializeData> clazz = (Class<SerializeData>) serializeData.getClass();
        LinkedBuffer linkedBuffer = LinkedBuffer.allocate(1024 * 4);
        Schema<SerializeData> schema = RuntimeSchema.getSchema(clazz);
        return ProtostuffIOUtil.toByteArray(serializeData, schema, linkedBuffer);
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserialize(byte[] bytes) {
        Schema<SerializeData> schema = RuntimeSchema.getSchema(SerializeData.class);
        SerializeData serializeData = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(bytes, serializeData, schema);
        return (T) serializeData.target;
    }
}
